package com.ts.api.http.org.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.digest.DigestType;
import com.gitee.apanlh.util.algorithm.digest.SHA;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.http.org.entity.apply.OrgApplyHeFeiJiuFu;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.org.handler.ApiOrgPhoneMd5ConvertHandler;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5Apply;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5DataExchange;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 *  合肥玖富-安心50混合
 *
 *  @author 李源聪
 */
@ApiPlan(productId = "57", type = ApiPlanConvertType.ORG_PHONE_MD5)
public class ApiOrgPhoneMd5HeFeiJiuFu implements ApiOrgPhoneMd5ConvertHandler {
    private static final String CHANNEL = "jiufuanxin";
    private static final String SECRET = "Q1CESKU3hTh4g0wOUyV41IY55RWyoLBS";

    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        Map<Object, Object> newMap = new LinkedHashMap<>();
        newMap.put("mobile", apiDataExchangeParameter.getPhoneMd5());
        return newMap;
    }

    public RespOrgPhoneMd5DataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (data == null) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(data.getInteger("is_exit"), 0)) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        return RespOrgPhoneMd5DataExchange.ofSuc();
    }

    public Object apply(ApiApplyParameter apiApplyParameter) throws IOException {
        OrgApplyHeFeiJiuFu apply = new OrgApplyHeFeiJiuFu();
        apply.setChannel(CHANNEL);
        apply.setToken(this.getToken(apiApplyParameter.getReqId()));
        apply.setName(apiApplyParameter.getUserName());
        apply.setMobile(apiApplyParameter.getPhone());
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        apply.setAge(apiFieldConverter.getAgeInt());
        //  申请额度
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 30000)
                .when(apiApplyParameter.getLoanAmount(), "2", 50000)
                .when(apiApplyParameter.getLoanAmount(), "3", 100000)
                .when(apiApplyParameter.getLoanAmount(), "4", 200000)
                .end();
        apply.setMoney_demand(money);
        // 城市
        apply.setCity(apiApplyParameter.getCity().replace("市", ""));
        //  房
        if (ValidParam.isNotEmpty(apiApplyParameter.getRealEstateInfo())) {
            String house = ChooseEq.create()
                    .when(apiApplyParameter.getRealEstateInfo(), "1", "N")
                    .when(apiApplyParameter.getRealEstateInfo(), "2", "Y")
                    .when(apiApplyParameter.getRealEstateInfo(), "3", "Y")
                    .when(apiApplyParameter.getRealEstateInfo(), "4", "Y")
                    .when(apiApplyParameter.getRealEstateInfo(), "5", "Y")
                    .when(apiApplyParameter.getRealEstateInfo(), "6", "Y")
                    .end("N");
            apply.setIs_house(house);
        }
        // 车
        if (ValidParam.isNotEmpty(apiApplyParameter.getCarInfo())) {
            String car = ChooseEq.create()
                    .when(apiApplyParameter.getCarInfo(), "1", "N")
                    .when(apiApplyParameter.getCarInfo(), "2", "Y")
                    .when(apiApplyParameter.getCarInfo(), "3", "Y")
                    .when(apiApplyParameter.getCarInfo(), "4", "Y")
                    .end("N");
            apply.setIs_car(car);
        }
        // 保单
        if (ValidParam.isNotEmpty(apiApplyParameter.getInsurancePolicy())) {
            String baodanIs = ChooseEq.create()
                    .when(apiApplyParameter.getInsurancePolicy(), "1", "N")
                    .when(apiApplyParameter.getInsurancePolicy(), "2", "Y")
                    .when(apiApplyParameter.getInsurancePolicy(), "3", "Y")
                    .when(apiApplyParameter.getInsurancePolicy(), "4", "Y")
                    .end("N");
            apply.setIs_insurance(baodanIs);
        }
        // 公积金
        if (ValidParam.isNotEmpty(apiApplyParameter.getProvidentFund())) {
            String gongjijin = ChooseEq.create()
                    .when(apiApplyParameter.getProvidentFund(), "1", "N")
                    .when(apiApplyParameter.getProvidentFund(), "2", "Y")
                    .when(apiApplyParameter.getProvidentFund(), "3", "Y")
                    .when(apiApplyParameter.getProvidentFund(), "4", "Y")
                    .end("N");
            apply.setIs_fund(gongjijin);
        }
        // 社保
        if (ValidParam.isNotEmpty(apiApplyParameter.getSocialSecurity())) {
            String shebao = ChooseEq.create()
                    .when(apiApplyParameter.getSocialSecurity(), "1", "N")
                    .when(apiApplyParameter.getSocialSecurity(), "2", "Y")
                    .when(apiApplyParameter.getSocialSecurity(), "3", "Y")
                    .when(apiApplyParameter.getSocialSecurity(), "4", "Y")
                    .end("N");
            apply.setIs_social(shebao);
        }
        //  企业是否有纳税
        apply.setIs_tax("N");
        //  企业是否开票
        apply.setIs_invoice("N");
        //  身份证号
        apply.setIdcard(apiApplyParameter.getIdcard());
        //  芝麻分
        apply.setZhimascore(apiFieldConverter.getSesameCreditText());
        return apply;
    }

    public RespOrgPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("responseCode"), 0)) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        return RespOrgPhoneMd5Apply.ofSuc();
    }

    private String getToken(String random) throws IOException {
        String url = "http://146.56.228.45/api/index/gettoken";
        Map<Object, Object> newMap = new LinkedHashMap<>();
        long times = System.currentTimeMillis();
        newMap.put("channel", CHANNEL);
        newMap.put("random", random);
        newMap.put("times", times);
        String data = CHANNEL + ";" + SECRET + ";" + random + ";" + times;
        String sign = SHA.create(DigestType.SHA_1).digestToHex(data);
        newMap.put("sign", sign);
        CloseableHttpResponse response = null;
        String token;
        try (CloseableHttpClient httpclient = HttpClients.createDefault()){
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> params = new ArrayList<>();
            newMap.forEach((k, v) -> params.add(new BasicNameValuePair(k.toString(), v.toString())));
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
            JSONObject jsonObject = JsonUtils.get(result);
            token = jsonObject.getJSONObject("data").getString("token");
        } catch (Exception e) {
            throw new RuntimeException("获取token失败: " + e.getMessage(), e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return token;
    }
}
